#include "CDalRecord.h"

#include <iostream>

#include "core/lib/sqlite/sqlite3.h"

CDalRecord::CDalRecord()
{
  pStatement = NULL;
}

CDalRecord::~CDalRecord()
{
  if (pStatement)
  {
    sqlite3_finalize(pStatement);
    std::cout << "CDalRecord: Statement Finalized" << std::endl;
  }
}

CDalRecord::CDalRecord(sqlite3_stmt *stmt)
{
  prepareRecord(stmt);
}

void CDalRecord::prepareRecord(sqlite3_stmt *stmt)
{
  pStatement = stmt;

  for (int i = 0; i < sqlite3_column_count(pStatement); i++)
  {
    std::string columnName = sqlite3_column_name(pStatement, i);
    mColumnNumber[columnName] = i;

    //std::cout << "Column ID " << i << ": " << columnName.c_str() << std::endl;
  }

  rowCount = 0;
  while (sqlite3_step(pStatement) != SQLITE_DONE)
  {
    ++rowCount;
  }

  sqlite3_reset(pStatement);
}

bool CDalRecord::readNext()
{
  int status = sqlite3_step(pStatement);

  if (status == SQLITE_DONE)
    return false;
  else
    return true;
}

int CDalRecord::getRowCount()
{
  return rowCount;
}

int CDalRecord::getColumnNumber(const char * field)
{
  if (mColumnNumber.find(field) == mColumnNumber.end())
  {
    std::cout << "Invalid field name: " << field << std::endl;
    return -1; // Sqlite will cater this case
  }
  else
  {
    return mColumnNumber[field];
  }
}

int CDalRecord::getInt(const char * field)
{
  return sqlite3_column_int(pStatement, getColumnNumber(field));
}

const unsigned char * CDalRecord::getString(const char * field)
{
  return sqlite3_column_text(pStatement, getColumnNumber(field));
}

double CDalRecord::getDouble(const char * field)
{
  return sqlite3_column_double(pStatement, getColumnNumber(field));
}

CDalRecord* CDalRecord::operator=(sqlite3_stmt *stmt)
{
  prepareRecord(stmt);
  return this;
}
